package tech.aistar.filter;

import tech.aistar.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Ray
 * @version 1.0
 * @description:本类用来演示:
 * @date 2019/9/9  15:20
 */
@WebFilter(urlPatterns = "/phone/*")
public class CheckUserLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //需要进行一个转换
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //判断用户是否登录
        User user = (User) req.getSession().getAttribute("user");
        if(null == user){
            //重定向到登录界面
            resp.sendRedirect(req.getContextPath()+"/prj/user/login.jsp?error=2");
        }else{
            //此代码行以上的代码是进入目标servlet之前执行的
            //决定是否放行
            filterChain.doFilter(req,resp);
        }
    }

    @Override
    public void destroy() {

    }
}
